<template>
  <div class="toolbar-wrap">
    <a-tooltip class="item" effect="dark" title="删除 ">
      <!-- <a-button
        icon="delete"
        :disabled="selectItem === ''"
        shape="circle"
        @click="deleteItem"
      /> -->
      <a-button
        :disabled="selectItem === ''"
        shape="circle"
        @click="deleteItem"
      >
        <template #icon><DeleteOutlined /></template>
      </a-button>
    </a-tooltip>
    <a-divider type="vertical"></a-divider>

    <a-tooltip class="item" effect="dark" title="放大">
      <!-- <a-button
        icon="add-circle-fill"
        :disabled="zoom >= 1.8"
        shape="circle"
        @click="zoomIn"
      /> -->
      <a-button shape="circle" :disabled="zoom >= 1.8" @click="zoomIn">
        <template #icon><ZoomInOutlined /></template>
      </a-button>
    </a-tooltip>
    <a-divider type="vertical"></a-divider>

    <a-tooltip class="item" title="缩小">
      <!-- <a-button
        icon="zoom-out"
        :disabled="zoom <= 0.3"
        shape="circle"
        @click="zoomOut"
      /> -->
      <a-button :disabled="zoom <= 0.3" shape="circle" @click="zoomOut">
        <template #icon><ZoomOutOutlined /></template>
      </a-button>
    </a-tooltip>
    <a-divider type="vertical"></a-divider>
    <!-- <a-button icon="copy" :disabled="showCopy" shape="circle" @click="copy" /> -->
    <a-button :disabled="showCopy" shape="circle" @click="copy">
      <template #icon><SnippetsOutlined /></template>
    </a-button>
    <a-divider type="vertical"></a-divider>

    <!-- <a-button icon="file-done">安装</a-button> -->
    <a-button>
      <template #icon><AndroidOutlined /></template>
      安装
    </a-button>
    <a-divider type="vertical"></a-divider>
    <!-- <a-button icon="delete">卸载</a-button> -->
    <a-button>
      <template #icon><DeleteOutlined /></template>
      卸载
    </a-button>
    <a-divider type="vertical"></a-divider>
    <!-- <a-button icon="file-done" @click="save">保存</a-button> -->
    <a-button @click="save">
      <template #icon><FolderOpenOutlined /></template>
      保存
    </a-button>
    <a-divider type="vertical"></a-divider>

    <!-- <a-button icon="appstore" type="primary" @click="flowSettingVisible = true">
      属性
    </a-button> -->
    <a-button @click="flowSettingVisible = true">
      <template #icon><SettingOutlined /></template>
      属性
    </a-button>
    <vxe-modal resize width="800" title="流程属性" v-model="flowSettingVisible">
      <template v-slot>
        <div class="p-1">
          <a-tabs size="small" type="card">
            <a-tab-pane :forceRender="true" key="1" tab="基本信息">
              <a-form
                ref="basicInfoForm"
                :model="basicInfoForm"
                :rules="basicInfoFormRules"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 18 }"
              >
                <a-form-item label="流程ID">
                  <a-input
                    v-model:value="basicInfoForm.id"
                    readonly="readonly"
                    disabled
                  />
                </a-form-item>
                <a-form-item ref="flowType" label="流程分类" name="flowType">
                  <a-select
                    placeholder="请选择"
                    v-model:value="basicInfoForm.flowType"
                    style=""
                  >
                    <a-select-option
                      v-for="item in flowTypeData"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item ref="name" label="流程名称" name="name">
                  <a-input v-model:value="basicInfoForm.name" />
                </a-form-item>
                <a-form-item label="备注">
                  <a-textarea v-model:value="basicInfoForm.note"></a-textarea>
                </a-form-item>
              </a-form>
            </a-tab-pane>
            <a-tab-pane key="2" tab="数据连接">
              <vxe-toolbar>
                <template v-slot:buttons>
                  <vxe-button @click="insertEvent()">
                    <template #icon><PlusSquareOutlined /></template>
                    新增
                  </vxe-button>
                </template>
              </vxe-toolbar>

              <vxe-table
                style=""
                border
                show-overflow
                keep-source
                ref="xTable"
                class="my_table_insert"
                max-height="400"
                :data="tableData"
                @cell-click="cellClick"
                :edit-config="{
                  trigger: 'click',
                  mode: 'cell',
                  icon: 'fa fa-pencil',
                }"
              >
                <vxe-table-column
                  field="linkId"
                  title="数据库连接"
                  :edit-render="{
                    name: '$select',
                    options: databaseData,
                    events: { change: databaseChange },
                  }"
                ></vxe-table-column>

                <vxe-table-column
                  field="tableName"
                  title="数据表"
                  :edit-render="{
                    name: '$select',
                    options: tableNameData,
                    events: { change: tableNameChange },
                  }"
                ></vxe-table-column>

                <vxe-table-column
                  field="primaryKey"
                  title="主键"
                  :edit-render="{ name: '$select', options: fieldData }"
                ></vxe-table-column>

                <vxe-table-column title="操作" sortable>
                  <template v-slot="{ row }">
                    <a @click="removeEvent(row)">删除</a>
                  </template>
                </vxe-table-column>
              </vxe-table>
            </a-tab-pane>
            <a-tab-pane :forceRender="true" key="3" tab="标识字段">
              <a-form
                ref="FieldForm"
                :model="fieldform"
                :rules="fieldrules"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 18 }"
              >
                <a-form-item ref="linkId" label="数据连接" name="linkId">
                  <a-select
                    placeholder="请选择"
                    v-model:value="fieldform.linkId"
                    @change="identificationDBChange"
                    style=""
                  >
                    <a-select-option
                      v-for="item in databaseData"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item ref="tableName" label="数据表" name="tableName">
                  <a-select
                    placeholder="请选择"
                    v-model:value="fieldform.tableName"
                    @change="identificationTableChange"
                    style=""
                  >
                    <a-select-option
                      v-for="item in identificationTableData"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>

                <a-form-item
                  ref="primaryKey"
                  label="完成标识"
                  name="primaryKey"
                >
                  <a-select
                    placeholder="请选择"
                    v-model:value="fieldform.primaryKey"
                    style=""
                  >
                    <a-select-option
                      v-for="item in identificationFieldData"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item ref="value" label="标识值" name="value">
                  <a-input v-model:value="fieldform.value" />
                </a-form-item>
              </a-form>
            </a-tab-pane>
            <a-tab-pane :forceRender="true" key="4" tab="显示控制">
              <vxe-table stripe height="450" :data="mainTableSetting">
                <vxe-table-column width="80px" title="字段取值">
                  <template v-slot="{ row }">
                    <a-checkbox
                      v-if="row.value"
                      v-model:checked="row.isVisible"
                    >
                      <span style="margin-left: 3px">{{ row.value }}</span>
                    </a-checkbox>
                  </template>
                </vxe-table-column>

                <vxe-table-column type="expand" width="45px">
                  <template #content="{ row, rowIndex }">
                    <a-button
                      type="primary"
                      @click="handleAdd(rowIndex)"
                      class="mb-1"
                    >
                      新增
                    </a-button>
                    <vxe-table stripe :data="row.items">
                      <vxe-table-column title="取值字段">
                        <template v-slot="{ row }">
                          <a-input v-model:value="row.value"></a-input>
                        </template>
                      </vxe-table-column>

                      <vxe-table-column title="显示名称">
                        <template v-slot="{ row }">
                          <a-input v-model:value="row.lable"></a-input>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column width="90px" title="对齐方式">
                        <template v-slot="{ row }">
                          <a-select
                            style="width: 80px"
                            v-model:value="row.algin"
                          >
                            <a-select-option value="left">
                              右对齐
                            </a-select-option>
                            <a-select-option value="right">
                              左对齐
                            </a-select-option>
                            <a-select-option value="center">
                              居中
                            </a-select-option>
                          </a-select>
                        </template>
                      </vxe-table-column>

                      <vxe-table-column width="80px" title="宽度">
                        <template v-slot="{ row }">
                          <a-input-number
                            style="width: 68px"
                            placeholder="请输入"
                            v-model:value="row.width"
                          ></a-input-number>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column width="80px" title="顺序">
                        <template v-slot="{ row }">
                          <a-input-number
                            style="width: 68px"
                            placeholder="请输入"
                            v-model:value="row.sort"
                          ></a-input-number>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column
                        align="center"
                        width="50px"
                        title="跳转"
                      >
                        <template v-slot="{ row }">
                          <a-checkbox v-model:checked="row.isJump"></a-checkbox>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column
                        align="center"
                        width="50px"
                        title="隐藏"
                      >
                        <template v-slot="{ row }">
                          <a-checkbox
                            v-model:checked="row.isHiddin"
                          ></a-checkbox>
                        </template>
                      </vxe-table-column>
                      <vxe-table-column width="80px" title="操作">
                        <template v-slot="{ row }">
                          <a @click="handleDlete(row, rowIndex)">删除</a>
                        </template>
                      </vxe-table-column>
                    </vxe-table>
                  </template>
                </vxe-table-column>

                <vxe-table-column width="100px" title="显示名称">
                  <template v-slot="{ row }">
                    <a-input v-model:value="row.lable"></a-input>
                  </template>
                </vxe-table-column>
                <vxe-table-column width="90px" title="对齐方式">
                  <template v-slot="{ row }">
                    <a-select style="width: 80px" v-model:value="row.algin">
                      <a-select-option value="left">右对齐</a-select-option>
                      <a-select-option value="right">左对齐</a-select-option>
                      <a-select-option value="center">居中</a-select-option>
                    </a-select>
                  </template>
                </vxe-table-column>

                <vxe-table-column width="80px" title="宽度">
                  <template v-slot="{ row }">
                    <a-input-number
                      style="width: 68px"
                      placeholder="请输入"
                      v-model:value="row.width"
                    ></a-input-number>
                  </template>
                </vxe-table-column>
                <vxe-table-column width="80px" title="顺序">
                  <template v-slot="{ row }">
                    <a-input-number
                      style="width: 68px"
                      placeholder="请输入"
                      v-model:value="row.sort"
                    ></a-input-number>
                  </template>
                </vxe-table-column>
                <vxe-table-column align="center" width="50px" title="跳转">
                  <template v-slot="{ row }">
                    <a-checkbox v-model:checked="row.isJump"></a-checkbox>
                  </template>
                </vxe-table-column>
                <vxe-table-column align="center" width="50px" title="隐藏">
                  <template v-slot="{ row }">
                    <a-checkbox v-model:checked="row.isHiddin"></a-checkbox>
                  </template>
                </vxe-table-column>
                <vxe-table-column width="100px" title="类型">
                  <template v-slot="{ row }">
                    <a-select style="width: 90px" v-model:value="row.type">
                      <a-select-option value="0">不处理</a-select-option>
                      <a-select-option value="1">数据字典</a-select-option>
                      <a-select-option value="2">sql语句</a-select-option>
                      <a-select-option value="3">静态数据</a-select-option>
                    </a-select>
                  </template>
                </vxe-table-column>
                <vxe-table-column title="说明" field="note"></vxe-table-column>
              </vxe-table>
            </a-tab-pane>
          </a-tabs>
          <div style="text-align: center">
            <a-divider></a-divider>
            <a-button @click="flowSettingUpdate" type="primary">确定</a-button>
            <a-button @click="flowSettingVisible = false" class="ml-2"  >
              取消
            </a-button>
          </div>
        </div>
      </template>
    </vxe-modal>

    <vxe-modal resize width="600" v-model="organizeSelectVisible">
      <template v-slot>
        <OrganizeSelect></OrganizeSelect>
      </template>
    </vxe-modal>
  </div>
</template>

<script>
  import { only } from '../../utils'
  import { getGuid } from '@/utils/util'
  import { GetDictByPid } from '@/api/dictionary/api'
  import { Gets, Gettables, Getfileds } from '@/api/databaselink/api'
  import OrganizeSelect from '@/mycomponents/organize/organizeSelect'
  import {
    ZoomOutOutlined,
    ZoomInOutlined,
    SnippetsOutlined,
    AndroidOutlined,
    DeleteOutlined,
    FolderOpenOutlined,
    SettingOutlined,
    PlusSquareOutlined,
  } from '@ant-design/icons-vue'
  export default {
    name: 'Toolbar',
    inject: ['FlowDT'],
    components: {
      OrganizeSelect,
      ZoomOutOutlined,
      ZoomInOutlined,
      SnippetsOutlined,
      AndroidOutlined,
      DeleteOutlined,
      FolderOpenOutlined,
      SettingOutlined,
      PlusSquareOutlined,
    },

    props: {
      // eslint-disable-next-line vue/require-prop-types
      selectItem: {
        required: true,
      },
      nodeModel: {
        //被选中节点数据
        type: Object,
        default: () => ({}),
      },
      edgeModel: {
        //被选中边数据
        type: Object,
        default: () => ({}),
      },
      flowData: {
        type: Object,
        default: () => ({}),
      },
    },
    data() {
      return {
        organizeSelectVisible: false,
        tableData: [], // 数据连接table数据
        databaseData: [], // 数据库列表数据
        tableNameData: [], // 数据库表格数据
        fieldData: [], // 表格字段数据
        identificationTableData: [], // 数据库表格数据
        identificationFieldData: [], //   表格字段数据
        mainTableSetting: [], //   主表字段设置
        flowSettingVisible: false, //流程model是否可见
        // 流程设置基本信息
        basicInfoForm: {
          id: getGuid(),
          name: '',
          flowType: '',
        },
        // 流程设置基本信息验证规则
        basicInfoFormRules: {
          name: [
            { required: true, message: '名称不可为空！', trigger: 'blur' },
          ],
          flowType: [
            { required: true, message: '流程类型不可为空！', trigger: 'blur' },
          ],
        },
        // 流程设置标识字段
        fieldform: {
          linkId: '',
          tableName: '',
          primaryKey: '',
          value: '',
        },
        // 流程设置标识字段验证规则
        fieldrules: {
          linkId: [
            {
              required: true,
              message: '数据库连接不可为空！',
              trigger: 'blur',
            },
          ],
          tableName: [
            { required: true, message: '表格名称不可为空！', trigger: 'blur' },
          ],
          primaryKey: [
            { required: true, message: '字段不可为空！', trigger: 'blur' },
          ],
          value: [
            {
              required: true,
              message: '完成标识值不可为空！',
              trigger: 'blur',
            },
          ],
        },
        flowTypeData: [], // 流程分类
        zoom: 1, //g6大小
        copyItem: '', // 赋值节点的item信息
      }
    },
    computed: {
      showCopy() {
        return !(this.selectItem && this.selectItem.getType() === 'node')
      },
    },
    created() {
      var that = this
      // console.log('flowData', this.flowData)
      if (this.flowData.id != null) {
        this.basicInfoForm.flowType = this.flowData.dictId
        this.basicInfoForm.name = this.flowData.name
        this.basicInfoForm.id = this.flowData.id
        this.basicInfoForm.note = this.flowData.note
        this.tableData = this.flowData.dataBases
        this.fieldform = this.flowData.identityField
        this.mainTableSetting = this.flowData.mainTableSetting
        // console.log("first-maingTable",this.mainTableSetting)
      }
      // 获取标识字段的select的下拉框数据

      if (that.$route.query.id != undefined) {
        that.identificationDBChange(that.flowData.identityField.linkId)
        that.identificationFieldData = []
        Getfileds({
          id: that.fieldform.linkId,
          table: that.flowData.identityField.tableName,
        }).then((res) => {
          res.content.forEach((element) => {
            that.identificationFieldData.push({
              label: element.columnName,
              value: element.columnName,
              note: element.note,
            })
          })
        })
      }

      // 获取流程分类列表
      GetDictByPid().then((res) => {
        if (res.isSuccess) {
          that.flowTypeData = res.content
        }
      })
      // 获取数据库列表
      Gets().then((res) => {
        if (res.isSuccess) {
          that.databaseData = []
          res.content.items.forEach((element) => {
            that.databaseData.push({
              label: element.name,
              value: element.id,
            })
          })
        }
      })
    },
    methods: {
      handleAdd(rowIndex) {
        var items = this.mainTableSetting[rowIndex].items
        if (items === undefined) {
          items = []
        }
        const record = {}
        items.push(record)
      },
      handleDlete(row, rowIndex) {
        // 删除数组中的对象
        const Fields = [...this.mainTableSetting[rowIndex].items]
        this.mainTableSetting[rowIndex].items = Fields.filter(
          (item) => item._XID !== row._XID
        )
      },
      //单元格被点击触发
      cellClick(cell) {
        var that = this
        if (cell._columnIndex == 1) {
          var resultData = []

          Gettables({ id: cell.row.linkId }).then((res) => {
            if (res.isSuccess) {
              res.content.forEach((element) => {
                resultData.push({
                  label: element.name,
                  value: element.name,
                })
              })
              that.tableNameData = resultData
            }
          })
        }
        if (cell._columnIndex == 2) {
          resultData = []
          Getfileds({ id: cell.row.linkId, table: cell.row.tableName }).then(
            (res) => {
              if (res.isSuccess) {
                res.content.forEach((element) => {
                  resultData.push({
                    label: element.columnName,
                    value: element.columnName,
                  })
                })

                that.fieldData = resultData
              }
            }
          )
        }
      },

      // 流程配置改变确认
      flowSettingUpdate() {
        var that = this
        console.log('error submit!!')
        var isCorrect = true
        this.$refs.basicInfoForm.validate((valid) => {
          if (!valid) {
            isCorrect = false
            that.$message.error('基本信息验证失败')
          }
        })
        this.$refs.FieldForm.validate((valid) => {
          if (!valid) {
            isCorrect = false
            that.$message.error('标识字段验证失败！')
          }
        })
        if (isCorrect) {
          that.$message.success('流程配置修改成功！')
          that.flowSettingVisible = false
          that.tableNameData =
            this.$refs.xTable === undefined
              ? this.tableData
              : this.$refs.xTable.afterFullData
          that.$emit(
            'childByValue',
            this.$refs.xTable === undefined
              ? this.tableData
              : this.$refs.xTable.afterFullData
          )
        }
      },

      // 标识字段的数据库改变事件
      identificationDBChange(value) {
        var that = this
        that.identificationTableData = []
        Gettables({ id: value }).then((res) => {
          res.content.forEach((element) => {
            that.identificationTableData.push({
              label: element.name,
              value: element.name,
            })
          })
        })
      },
      // 标识字段的数据表改变事件
      identificationTableChange(value) {
        var that = this
        that.identificationFieldData = []
        Getfileds({ id: that.fieldform.linkId, table: value }).then((res) => {
          that.mainTableSetting = []
          res.content.forEach((element) => {
            that.identificationFieldData.push({
              label: element.columnName,
              value: element.columnName,
              note: element.note,
            })
            that.mainTableSetting.push({
              value: element.columnName,
              note: element.note,
              items: [],
            })
          })
        })
      },

      // table表格的数据库连接改变事件
      databaseChange({ row }) {
        var that = this
        that.tableNameData = []
        Gettables({ id: row.linkId }).then((res) => {
          console.log(res)
          res.content.forEach((element) => {
            that.tableNameData.push({
              label: element.name,
              value: element.name,
            })
          })
        })
        console.log(this.tableNameData)
      },

      // table表格的数据表改变事件
      tableNameChange({ row }) {
        var that = this
        that.fieldData = []
        Getfileds({ id: row.linkId, table: row.tableName }).then((res) => {
          console.log(res)
          res.content.forEach((element) => {
            that.fieldData.push({
              label: element.columnName,
              value: element.columnName,
            })
          })
        })
      },
      // 删除table表格一行数据
      removeEvent(row) {
        this.$refs.xTable.remove(row)
      },
      // 新增table表格一行数据
      async insertEvent(row) {
        const record = {
          linkId: '请选择',
        }
        const { row: newRow } = await this.$refs.xTable.insertAt(record, row)
        await this.$refs.xTable.setActiveCell(newRow, 'sex')
      },

      // 保存修改流程
      save() {
        // console.log(this.FlowDT.$graph.save())
        //  console.log('this.mainTableSetting', this.mainTableSetting,)
        this.$nextTick(() => {
          this.FlowDT.$emit('save', this.FlowDT.$graph.save(), {
            id: this.basicInfoForm.id,
            name: this.basicInfoForm.name,
            dictId: this.basicInfoForm.flowType,
            note: this.basicInfoForm.note,
            dataBases:
              this.$refs.xTable === undefined
                ? this.tableData
                : this.$refs.xTable.afterFullData,
            identityField: this.fieldform,
            mainTableSetting: this.mainTableSetting,
          })
        })
      },
      //--------------------g6编辑事件-------------------------

      copy() {
        //只有在有选中节点并且节点类型为node时生效由showCopy属性控制按钮是否禁用
        this.copyItem = this.selectItem.getModel()
        if (this.copyItem === '') return
        this.$nextTick(() => {
          this.FlowDT.$graph.add('node', {
            ...this.copyItem,
            id: only(),
            x: this.copyItem.x + 20,
            y: this.copyItem.y + 20,
          })
        })
      },
      zoomIn() {
        this.zoom += 0.1
        this.$nextTick(() => {
          this.FlowDT.$graph.zoomTo(this.zoom)
        })
      },
      zoomOut() {
        this.zoom -= 0.1
        this.$nextTick(() => {
          this.FlowDT.$graph.zoomTo(this.zoom)
        })
      },
      deleteItem() {
        this.$nextTick(() => {
          const nodeType = this.selectItem.getType()
          if (nodeType === 'edge') {
            this.FlowDT.$graph.remove(this.selectItem)
            this.FlowDT.selectItem = ''
          } else if (nodeType === 'node') {
            //找到当前节点所有关联边,并且移除
            this.selectItem.getEdges().forEach((edge) => {
              this.FlowDT.$graph.remove(edge)
            })
            //然后移除掉当前节点
            this.FlowDT.$graph.remove(this.selectItem)
            this.FlowDT.selectItem = ''
          }
        })
      },
    },
  }
</script>

<style>
  .ant-form-item {
    margin-bottom: 10px;
  }
</style>
